package models

import (
	"time"

	"github.com/astaxie/beego/orm"
)

//用户基础信息表字段（表：shop_users）
type User struct {
	Id         int64
	Phone      int64
	Password   string
	Nickname   string
	Created    time.Time
	Update     time.Time
	Login_date time.Time
	Login_num  int
}

//个人中心结构体
type Center struct {
	Id         int64
	Phone      int64
	Nickname   string
	Created    time.Time
	Update     time.Time
	Login_date time.Time
	Login_num  int64
	Integral   int64
	//未付款
	Unpaid_order_num int64
	//待发货
	Delivered_order_num int64
	//待评价
	Comment_order_num int64
	//待收货
	Received_orider_num int64
	//退款中
	Refund_orider_num int64
}

func (u *User) TableName() string {
	return "shop_users"
}

func init() {
	orm.RegisterModel(new(User), new(Center))
}

//用户注册
func UserRegisterByPhone(phone int64, password string) (int64, string, int64) {
	o := orm.NewOrm()
	var user = User{}
	var t = time.Now()
	user.Phone = phone
	user.Password = password
	user.Nickname = "shop30033"
	user.Created = t
	user.Update = t
	user.Login_date = t
	user.Login_num = 1
	//新增用户基础信息
	uid, err := o.Insert(&user)
	if err != nil {
		return CODE1001, MSG1001, 0
	} else {
		//新增用户积分账号信息
		_, inErr := o.Raw("INSERT INTO shop_users_integral (user_id,created,`update`) VALUES (?,?,?) ", uid, user.Created, user.Update).Exec()
		if inErr != nil {
			return CODE1001, MSG1001, 0
		}
		return CODE1000, MSG1000, uid
	}
}

//根据用户注册手机号码查询是否已注册
func CheckUserPhone(phone int64) (int64, string) {
	o := orm.NewOrm()
	user := User{}
	user.Phone = phone
	err := o.Read(&user, "phone")
	//假如查询为空则返回code:1000该号码可以注册，否则返回code:1003该号码已被注册
	if err == orm.ErrNoRows {
		return CODE1000, MSG1000
	} else {
		return CODE1003, MSG1003
	}
}

//检查该用户是否存在
func CheckUserLogin(phone int64, password string) (int64, string) {
	o := orm.NewOrm()
	user := User{}
	//根据用户手机和密码检测该用户是否存在
	err := o.QueryTable("shop_users").Filter("phone", phone).Filter("password", password).One(&user)
	// 没有找到记录
	if err == orm.ErrNoRows {
		return CODE1004, MSG1004
	} else {
		return CODE1000, MSG1000
	}
}

//根据手机号码获取用户个人资料
func GetUserDataByPhone(phone int64) (int64, string, *Center, int64) {
	o := orm.NewOrm()
	center := Center{}
	user := User{Phone: phone}
	err := o.Raw("SELECT su.id,su.phone,su.nickname,su.login_date,su.login_num,sui.integral FROM shop_users AS su LEFT JOIN shop_users_integral AS sui ON sui.user_id=su.id WHERE su.phone=?", phone).QueryRow(&center)

	// 假如没有找到记录，则返回code:1004 账号或密码错误
	if err != nil {
		return CODE1004, MSG1004, &center, 0
	} else {
		//根据用户手机获取userId存进Session
		_ = o.Read(&user, "phone")

		//用户每次登录都会添加1次登录记录
		var num int
		num = user.Login_num + 1
		o.Raw("update shop_users set login_num = ? where id = ?", num, user.Id).Exec()

		return CODE1000, MSG1000, &center, user.Id
	}
}

//根据用户ID查询个人中心信息
func GetUserCenterById(id interface{}) (int64, string, *Center) {
	o := orm.NewOrm()
	center := Center{}
	//根据ID获取个人信息
	err := o.Raw("SELECT su.*,sui.integral FROM shop_users AS su LEFT JOIN shop_users_integral AS sui ON sui.user_id=su.id WHERE su.id = ?", id).QueryRow(&center)

	//假如有数据继续查询个人订单统计,否则返回cdoe:1005 暂无数据
	if err != nil {
		return CODE1005, MSG1005, &center
	} else {
		//统计未支付订单
		_ = o.Raw("SELECT count(*) as unpaid_order_num FROM shop_order WHERE user_id=? AND is_pay=0", id).QueryRow(&center)

		//统计待发货订单
		_ = o.Raw("SELECT count(*) as delivered_order_num FROM shop_order WHERE user_id=? AND is_pay=1 AND is_delivery=0", id).QueryRow(&center)

		//统计待收货订单
		_ = o.Raw("SELECT count(*) as received_orider_num FROM shop_order WHERE user_id=? AND is_delivery=1 AND is_received=0", id).QueryRow(&center)

		//统计待评价订单
		_ = o.Raw("SELECT count(*) as comment_order_num FROM shop_order WHERE user_id=? AND is_received=1 AND is_evaluate=0", id).QueryRow(&center)

		//统计退款中订单
		_ = o.Raw("SELECT count(*) as refund_orider_num FROM shop_order WHERE user_id=? AND is_pay=1 AND is_refund=1", id).QueryRow(&center)
		return CODE1000, MSG1000, &center
	}
}

//修改昵称
func UpdateUserNicknameById(id interface{}, nickname string) (int64, string) {
	o := orm.NewOrm()
	var user = User{Nickname: nickname, Update: time.Now()}

	//根据用户ID修改个人昵称
	_, err := o.Raw("update shop_users set nickname = ?,`update` = ? where id = ?", user.Nickname, user.Update, id).Exec()

	//假如修改失败返回code:1006 系统出错
	if err != nil {
		return CODE1006, MSG1006
	} else {
		return CODE1000, MSG1000
	}
}

//根据旧密码检测是否存在
func CheckUserPasswordById(id interface{}, password string) (int64, string) {
	o := orm.NewOrm()
	user := User{}
	//根据用户ID和密码检测该用户是否存在
	err := o.QueryTable("shop_users").Filter("id", id).Filter("password", password).One(&user)
	// 没有找到记录
	if err == orm.ErrNoRows {
		return CODE1004, MSG1004
	} else {
		return CODE1000, MSG1000
	}
}

//修改用户密码
func UpdateUserPasswordById(id interface{}, newPassword string) (int64, string) {
	o := orm.NewOrm()
	var user = User{Password: newPassword, Update: time.Now()}

	//根据用户ID修改用户密码
	_, err := o.Raw("update shop_users set password = ?,`update` = ? where id = ?", user.Password, user.Update, id).Exec()

	//假如修改失败返回code:1006 系统出错
	if err != nil {
		return CODE1006, MSG1006
	} else {
		return CODE1000, MSG1000
	}
}
